You can get the pre-processor to selectively pass on parts of your program to the compiler. This is very useful when you are developing something and want to add additional debugging code.
The decision is made depending on whether a particular symbol has been defined previously, for example:
#ifdef debug beep () ; #endif
If debug had been defined previously the beep function call is passed to the compiler. If this symbol does not exist all the text between the #ifdef and the #endif is removed by the pre-processor and the compiler never sees it. This means that I can turn all my debug statements on simply by typing:
#define debug 1
- at the beginning of the program and then rebuilding it. Note that the translation that I give to debug is not important, merely the fact that it has been defined.
You can add an else part if you wish:
#ifdef friendly lcd_print ( "You made a mistake." );
#else LCD_print ( "You idiot!" ) ; #endif
Remember that these decisions are not made when the program runs, they control what the program actually contains.
Another popular use for conditional compilation is the building of code which can be customized for various different machines. A particular compiler often has a number of words predefined. Your source can check for these and then include code to customize the program for that particular version. This makes writing portable code a lot easier.
On the right you can see how I have created a multi-lingual version of my program. If the symbol ENGLISH is defined the compiler is given the English version of the string. If the FRENCH symbol is defined the French version is used. Note that this is not a decision which the compiler actually makes, it is determined by the code which the compiler receives.
main.c.
#define ENGLISH #ifdef ENGLISH const char hello [] = 'h','e', 'l','l','o',0x00 ; #endif #ifdef FRENCH const char hello [] = 'b','o', 'n','j','o','u','r', 0x00 ; #endif lcd_print ( hello ) ;
COMPILER
const char hello [] = 'h','e', 'l','l','o',0x00 ; lcd_print ( hello ) ;